<?php
defined('BASEPATH') OR exit('No direct script access allowed');

define('ATTACHMENT_ROOT', FCPATH .'upload');

class Utility extends Backend {

    public $type;
    public $dest_dir;
    public $setting;

    public function __construct()
    {
        parent::__construct();

        $this->load->model('attachment_model');
        $this->load->helper(array('uploader','ihttp'));
        
        $type=$this->input->cookie("__fileupload_type");
        $type= in_array($type, array('image','audio','video')) ? $type : 'image';
        $this->type=$type;
        $option = array();
        $option = array_elements(array('uploadtype', 'global', 'dest_dir'), $_POST);
        if(isset($option['width'])) $option['width'] = intval($option['width']);
        $option['global'] = $this->input->cookie("__fileupload_global");
        if (!empty($option['global']) ) {
            $result['message'] = '没有向 global 文件夹上传文件的权限.';
            die(json_encode($result));
        }
        $dest_dir=$this->input->cookie("__fileupload_dest_dir");
        if (preg_match('/^[a-zA-Z0-9_\/]{0,50}$/', $dest_dir, $out)) {
            $dest_dir = trim($dest_dir, '/');
            $pieces = explode('/', $dest_dir);
            if(count($pieces) > 3){
                $dest_dir = '';
            }
        } else {
            $dest_dir = '';
        }
        $this->dest_dir=$dest_dir;

        $setting = array("limit"=>6*1024);

        if (isset($option['global']) && !empty($option['global'])) {
            $setting['folder'] = "{$type}s/global/";
            if (! empty($dest_dir)) {
                $setting['folder'] .= '/' . $dest_dir . '/';
            }
        } else {
            $setting['folder'] = "{$type}s";
            if (empty($dest_dir)) {
                $setting['folder'] .= '/' . date('Y/m/');
            } else {
                $setting['folder'] .= '/' . $dest_dir . '/';
            }
        }
        $this->setting=$setting;
    }

    public function upload()
    {
        if (empty($_FILES['file']['name'])) {
            $result['message'] = '上传失败, 请选择要上传的文件！';
            die(json_encode($result));
        }
        if ($_FILES['file']['error'] != 0) {
            $result['message'] = '上传失败, 请重试.';
            die(json_encode($result));
        }
        $ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
        $ext = strtolower($ext);
        $size = intval($_FILES['file']['size']);
        $originname = $_FILES['file']['name'];
        $filename = file_random_name(ATTACHMENT_ROOT . '/' . $this->setting['folder'], $ext);
        $file = file_upload($_FILES['file'], $this->type, $this->setting['folder'] . $filename);
        if (is_error($file)) {
            $result['message'] = $file['message'];
            die(json_encode($result));
        }
        $pathname = $file['path'];
        $fullname = ATTACHMENT_ROOT . '/' . $pathname;
        $this->save_item($originname,$ext,$fullname,$pathname);
    }

    public function fetch(){
        $url = trim($this->input->get('url'));
        $resp = ihttp_get($url);
        if (is_error($resp)) {
            $result['message'] = '提取文件失败, 错误信息: ' . $resp['message'];
            die(json_encode($result));
        }
        if (intval($resp['code']) != 200) {
            $result['message'] = '提取文件失败: 未找到该资源文件.';
            die(json_encode($result));
        }
        $ext = '';
        if ($this->type == 'image') {
            switch ($resp['headers']['Content-Type']) {
                case 'application/x-jpg':
                case 'image/jpeg':
                    $ext = 'jpg';
                    break;
                case 'image/png':
                    $ext = 'png';
                    break;
                case 'image/gif':
                    $ext = 'gif';
                    break;
                default:
                    $result['message'] = '提取资源失败, 资源文件类型错误.';
                    die(json_encode($result));
                    break;
            }
        } else {
            $result['message'] = '提取资源失败, 仅支持图片提取.';
            die(json_encode($result));
        }
        
        if (intval($resp['headers']['Content-Length']) > $this->setting['limit'] * 1024) {
            $result['message'] = '上传的媒体文件过大(' . sizecount($size) . ' > ' . sizecount($this->setting['limit'] * 1024);
            die(json_encode($result));
        }
        $originname = pathinfo($url, PATHINFO_BASENAME);
        $filename = file_random_name(ATTACHMENT_ROOT . '/' . $this->setting['folder'], $ext);
        $pathname = $this->setting['folder'] . $filename;
        $fullname = ATTACHMENT_ROOT . '/' . $pathname;
        mkdirs(dirname($fullname));
        if (file_put_contents($fullname, $resp['content']) == false) {
            $result['message'] = '提取失败.';
            die(json_encode($result));
        }
        $this->save_item($originname,$ext,$fullname,$pathname);
    }

    public function optionimage()
    {
        $config = get_system_settings(); 

        $return =["error"=>1,"msg"=>""];

        $file = $_FILES['file'];
        if (empty($file['name'])) {
            $return['msg'] = '上传失败, 请选择要上传的文件！';
        }
        else
        {
            $url=$this->input->post("orgfile");
            if(empty($url))
            {

                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $ext = strtolower($ext);
                $filename = file_random_name(ATTACHMENT_ROOT . '/' . $this->setting['folder'], $ext);
                $pathname = $this->setting['folder'] . $filename;
                $fullname = ATTACHMENT_ROOT . '/' . $pathname;
                move_uploaded_file($file['tmp_name'], $fullname);
                $return["error"]=0;
                $return["path"]=$config["urlpath"].'/'.$pathname;
                //$return["msg"]="no url submit";
            }
            else
            {
                $result=parse_url($url);
                $folder=substr(dirname($result["path"]),1)."/";
                $filename=pathinfo($url,PATHINFO_BASENAME);
                if(strstr($filename,"?"))
                {
                    $tmp=explode("?",$filename);
                    $filename=$tmp[0];
                }
               
                $pathname = $folder . $filename;
                $fullname = ATTACHMENT_ROOT . '/' . $pathname;
                mkdirs(dirname($fullname));
                move_uploaded_file($file['tmp_name'], $fullname);
                $return["error"]=0;
                $return["path"]=$config["urlpath"].'/'.$pathname;
    
            }
        }
        echo json_encode($return);
        die();
    }


    public function save_item($originname,$ext,$fullname,$pathname)
    {
        $config = get_system_settings(); 
        
        $info = array(
            'name' => $originname,
            'ext' => $ext,
            'filename' => $pathname,
            'attachment' => $pathname,
            'url' => $config["urlpath"].'/'.$pathname,
            'is_image' => $this->type == 'image' ? 1 : 0,
            'filesize' => filesize($fullname),
        );
        if ($this->type == 'image') {
            $size = getimagesize($fullname);
            $info['width'] = $size[0];
            $info['height'] = $size[1];
        } else {
            $size = filesize($fullname);
            $info['size'] = sizecount($size);
        }

        $data=array(
            'filename' => $originname,
            'attachment' => $pathname,
            'type' => $this->type == 'image' ? 1 : ($this->type == 'audio'||$this->type == 'voice' ? 2 : 3),
            "adminid"=>$this->ion_auth->logged_in()
        );
        $this->attachment_model->addattachment($data);
        die(json_encode($info));
    }

    public function fixed_pic()
    {
        $config = get_system_settings(); 

        $return=["error"=>1,"msg"=>""];
        $url=$this->input->post("url");
        if(empty($url))
        {
            $return["msg"]="no url submit";
        }
        else if(strstr($url,$config["urlpath"]))
        {
            $return["error"]=0;
            $return["path"]=$url;
        }
        else
        {
            $result=parse_url($url);
            //$ext = 'jpg';
            $folder=substr(dirname($result["path"]),1)."/";
            $filename=pathinfo($url,PATHINFO_BASENAME);
            if(strstr($filename,"?"))
            {
                $tmp=explode("?",$filename);
                $filename=$tmp[0];
            }
            //$filename.=".".$ext;
            
            $pathname = $folder . $filename;
            $fullname = ATTACHMENT_ROOT . '/' . $pathname;
            
            if(file_exists($fullname))
            {   
                $return["error"]=0;
                $return["path"]=$config["urlpath"].'/'.$pathname;
            }
            else
            {
                $resp = ihttp_get($url);
                if (is_error($resp)) {
                    $return["msg"]="fetch error";
                }else if (intval($resp['code']) != 200) {
                    $return["msg"]="server return error";
                }else{

                    mkdirs(dirname($fullname));
                    if (file_put_contents($fullname, $resp['content']) == false) {
                        $return["msg"]="save error";
                    }
                    else
                    {
                        $return["error"]=0;
                        $return["path"]=$config["urlpath"].'/'.$pathname;
                    }
                }
            }
        }
        echo json_encode($return);
        die();
    }

    public function local()
    {
        $types = array('image', 'audio', 'video');
        $typeindex = array('image' => 1, 'audio' => 2, 'video' => 3);

        $year = intval($this->input->get('year'));
        $month = intval($this->input->get('month'));
        $page = intval($this->input->get('page'));
        $page = max(1, $page);
        $size = $this->input->get('pagesize') ? intval($this->input->get('pagesize')) : 10;

        $result=$this->attachment_model->queryattachment($typeindex[$this->type],$this->dest_dir,$page,$size,$year,$month);
        $list=$result["data"];        
        $rlist=array();
        foreach ($list as &$item) {
            $item['url'] = tomedia($item['attachment']);
            $item['createtime'] = date('Y-m-d', strtotime($item['addtime']));
            unset($item['adminid']);
            unset($item['addtime']);
            $rlist[$item["id"]]=$item;
        }

        $total = $result["total"]; 
        iajax(0, array(
            'page' => pagination($total, $page, $size, '', array(
                'before' => '2',
                'after' => '2',
                'ajaxcallback' => 'null' 
            )),
            'items' => $rlist 
        ));
    }    

    public function delete()
    {
        $id = $this->input->get('id');
        if(empty($id)){
            $id = $this->input->post('id');
        }
        $media = $this->attachment_model->getattachmentbyid($id);
        if (empty($media)) {
            exit('文件不存在或已经删除');
        }

        $status = file_delete($media['attachment']);        
        if (is_error($status)) {
            exit($status['message']);
        }
        $this->attachment_model->deleteattachmentbyid($id);
        exit('success');
    }
    
}
